<?php
namespace common\models\info;

use common\component\BaseActiveRecord;
use common\component\Constant;
use common\utils\CommonUtil;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "{{%zt_seo}}".
 *
 * @property int $id
 * @property string $url
 * @property string $url_md5
 * @property string $keyword
 * @property string $title
 * @property string $description
 * @property int $status
 * @property int $type
 * @property int $cate_id
 * @property int $updated_at
 * @property int $created_at
 */
class Seo extends BaseActiveRecord
{

    const STATUS_ENABLE = 1;   //启用
    const STATUS_DISABLE = 0;  //禁用

    const SITE_MAP_TYPE_ARTICLE = 1;    #文章站点
    const SITE_MAP_TYPE_photo = 2;    #相册站点

    const TDK_PC = 1;   //pc端

    static $statusArr = [
        self::STATUS_DISABLE => '禁止',
        self::STATUS_ENABLE => '启用',
    ];

    static $statusDropArr = [
        ["id"=>0,'text'=>'请选择状态'],
        ["id"=>self::STATUS_DISABLE,'text'=>'禁用'],
        ["id"=>self::STATUS_ENABLE,'text'=>'启用'],
    ];


    public static $siteMapType = [
        ["id"=>0,"text" => '请选择站点类型'],
        ["id"=>self::SITE_MAP_TYPE_ARTICLE,"text" => '文章站点'],
        ["id"=>self::SITE_MAP_TYPE_photo,"text" => '相册站点'],
    ];

    public static $siteMapTypeArr = [
        self::SITE_MAP_TYPE_ARTICLE => '文章站点',
        self::SITE_MAP_TYPE_photo => '相册站点',
    ];


    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%zt_seo}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['type','created_at','updated_at','status','cate_id'], 'integer'],
            [['url_md5','title','keyword'], 'string', 'max' => 100],
            [['url'], 'string', 'max' => 225],
            [['description'], 'string'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => '序列',
            'url' => 'URL地址',
            'url_md5' => 'urlMD5加密',
            'keyword' => '关键字',
            'title' => '标题',
            'description' => '描述',
            'type' => 'SEO类型',
            'cate_id' => '站点类型',
            'status' => '状态',
            'updated_at' => '修改时间',
            'created_at' => '创建时间',
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    self::EVENT_BEFORE_INSERT => ['created_at'],
                    self::EVENT_BEFORE_UPDATE => ['updated_at']
                ]
            ]
        ];
    }

    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }

        $this->type = $this->type?:self::TDK_ALL;    //默认PC端和手机端同步
        if ($insert) {
            $this->updated_at = time();
        }
        //检查是否存在
        $url = trim($this->url);
        $where = ['and'];
        $where[] = ['=','url_md5',md5($url)];
        $where[] = ['&','type',$this->type];
        if ($insert) {
            if (static::find()->where($where)->exists()) {
                $this->addError("url","【".$this->url."】已存在");
                return false;
            }
        }else{
            $where[] =['!=','id',$this->id];
            if (static::find()->where($where)->exists()) {
                $this->addError("url","【".$this->url."】已存在");
                return false;
            }
        }

        //新增加的数据自动生成拼音
        $this->url_md5 = md5($url);
        return true;
    }

    public function afterFind()
    {
        parent::afterFind();
        if (\Yii::$app->controller->appEnd == Constant::END_BACK) {
            $this->ui();
        }
    }

    public function ui() {
        $this->ui["updated_at"] = date("Y-m-d H:i:s",$this->updated_at);
        $this->ui["created_at"] = date("Y-m-d H:i:s",$this->created_at);
        $this->ui["type"] = $this->typeView();
        $this->ui['status'] = self::$statusArr[$this->status];
        $this->ui['cate_id'] = $this->cate_id?self::$siteMapTypeArr[$this->cate_id]:'';
    }

    public function dataListTable($post) {
        //请求参数组装
        $where = ["and"];

        if (isset($post['status']) && $post['status']) {
            $where[] = ['=','status',$post['status']];
        }
        if (isset($post['type']) && $post['type']) {
            $where[] = ["&", "type", $post["type"]];
            $where[] = [">=", "type", $post["type"]];
        }
        if (isset($post['cate_id']) && $post['cate_id']) {
            $where[] = ['=','cate_id',$post['cate_id']];
        }
        if (isset($post['title']) && !empty($post['title'])) {
            $or_where =['or',['like','title',trim($post['title'])],['like','keyword',trim($post['title'])]];
            $query = self::find()->where($where)->andWhere($or_where);
        }else {
            $query = self::find()->where($where);
        }
        $dataArr = self::table($query,$post);
        return $dataArr;
    }

    /**
     * 实例化模型对像
     * @param $id
     * @return BaseActiveRecord|null|static
     */
    public static function modelById($id) {
        if (!$id) {
            $model = new self();
        }
        else {
            $model = static::findOne($id);
        }
        return $model;
    }


    /**
     * 实例化模型对像
     * @param $url
     * @param $type
     * @return BaseActiveRecord|null|static
     */
    public static function getDataByUrl($url,$type) {
        $key = md5(trim($url).$type);
        $data = CommonUtil::getCache(__CLASS__,$key);
        if (!$data) {
            $where = ['and'];
            $where[] = ['=','url_md5',md5(trim($url))];
            $where[] = ['=','status',self::STATUS_ENABLE];
            $where[] = ["&","type",$type];
            $data = static::find()
                ->where($where)
                ->asArray()
                ->one();
            if ($data) {
                CommonUtil::setCache(__CLASS__,$key,$data,3600);
            }
        }
        return $data;
    }

    public static function getTDK($url,$type=self::TDK_PC) {
        $data_back = [
            "title" =>'',
            "description" =>'',
            "keywords" =>'',
        ];
        preg_match("/article\/(([1-9][0-9]*){1,10}).html$/",$url,$is_article);  //判断路径来源是否是文章详情页
        preg_match("/category\/([a-z]{1,})/",$url,$is_category);  //判断路径来源是否是分类
        preg_match("/tag\/([a-z]{1,})/",$url,$is_tag);  //判断路径来源是否是话题
        //根据url获取到相应的seo数据
        $data = Seo::getDataByUrl($url,$type);
        $data_article = isset($is_article[1])&&$is_article[1]?Article::loadReleaseArticle($is_article[1]):[];
        if ($data) {
            if ($data['title'] == '*') {
                $data_back['title'] = $is_article?($data_article['title'].Constant::TITLE_SUFFIX):Constant::TITLE_MAIN;
            } else {
                $data_back['title'] = $data['title'];
            }

            if ($data['description'] == '*') {
                $data_back['description'] = $is_article?($data_article['summary']?:Constant::DESCRIPTION_MAIN):Constant::DESCRIPTION_MAIN;
            } else {
                $data_back['description'] = $data['description'];
            }

            $data_back['keywords'] = $data['keyword'];
        }
        elseif ($is_article){
            $data = $data_article;
            if ($data) {
                $data_back['title'] = $data["title"].Constant::TITLE_SUFFIX;  //获取标题
                $data_back['description'] = $data["summary"];  //获取描述
                $tag_ids = TagsRelation::arrTagIdsList($is_article[1]);
                $data['tags'] = [];
                foreach ($tag_ids as $id) {
                    $data["tags"][] = Tags::getFieldById($id,"tag_name");
                }
                if (count($data["tags"])) {
                    $tagsArr = array_column($data["tags"],"text");
                    $data_back['keywords'] = implode(" ",$tagsArr);    //获取关键字
                }
            }
        }
        elseif ($is_category) {
            $data_back['title'] = Constant::TITLE_CATEGORY;
            $data_back['keywords'] = Constant::KEYWORDS_CATEGORY;
            $data_back['description'] = Constant::DESCRIPTION_CATEGORY;
        }
        else {
            $data_back['title'] = Constant::TITLE_MAIN;
            $data_back['keywords'] = Constant::KEYWORDS_MAIN;
            $data_back['description'] = Constant::DESCRIPTION_MAIN;
        }
        return $data_back;
    }


    /**
     * 获取文章TDK
     * @param $id
     * @return mixed
     */
    public static function getTDKByArticle($id) {
        $key = "seo:article:id:".$id;
        $data_back = CommonUtil::getCache(__CLASS__,$key);
        if (!$data_back) {
            $data = Article::loadRowData($id);
            $data_back['title'] = $data["title"].Constant::TITLE_SUFFIX;  //获取标题
            $data_back['description'] = $data["summary"];  //获取描述
            $tag_ids = TagsRelation::arrTagIdsList($id);
            $data['tags'] = [];
            foreach ($tag_ids as $id) {
                $data["tags"][] = Tags::getFieldById($id,"tag_name");
            }
            if (count($data["tags"])) {
                $tagsArr = array_column($data["tags"],"text");
                $data_back['keywords'] = implode(" ",$tagsArr);    //获取关键字
            }else{
                $data_back['keywords'] = '';    //获取关键字
            }
            CommonUtil::setCache(__CLASS__,$key,$data_back);
        }
        return $data_back;
    }


    /**
     * 根据站点类型获取站点url
     * @param $type
     * @return array
     */
    public static function getSiteMapData($type) {
        $data = [];
        switch ($type) {
            case self::SITE_MAP_TYPE_ARTICLE:
                $where = ['and'];
                $where[] = ['=','status',Article::STATUS_PASS];
                $where[] = ['<=','release_at',time()];
                $res = Article::find()->select("id")->where($where)->asArray()->all();
                if ($res) {
                    foreach ($res as $key => $val) {
                        $data[] = rtrim(\Yii::$app->params['seo_url'], '/')."/article/".$val['id'].".html";
                    }
                }
                break;
        }
        return $data;
    }


    /**
     * @param $arr
     * @param array $res
     * @return array
     */
        public static function arrayValues ($arr,$res = array()) {
            $values = array_values($arr);
            $arr = array();
            foreach($values as $item){
                if(is_array($item)){
                $arr = array_merge($item,$arr);
                } else {
                    array_push($res, $item);
                }
            }
            if ($arr) {
                return self::arrayValues($arr,$res);
            } else {
                return array_values(array_unique($res));
            }
        }

}
